package com.yxkj.railservicer.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.RSAPublicUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.ScreenUtils;
import com.yxkj.railservicer.util.SysApplicationUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by sunyu on 2017/2/22.
 */

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TAG";


    private LinearLayout ll_login;
    private EditText et_login_name;
    private EditText et_login_password;
    private Button btn_login;
    private TextView tv_login_tellogin;
    private TextView tv_login_forget;

    private OkHttpClient client;
    private JSONUtil jsonUtil;

    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#2387f5"));
        SysApplicationUtil.getInstance().addActivity(this);
        initData();
        initEvent();
    }

    /**
     * 加载事件
     */
    private void initEvent() {

        btn_login.setOnClickListener(this);
        tv_login_tellogin.setOnClickListener(this);
        tv_login_forget.setOnClickListener(this);
        addLayoutListener(ll_login, btn_login);
    }

    /**
     * 加载数据
     */
    private void initData() {

        et_login_name = (EditText) findViewById(R.id.et_login_name);
        et_login_password = (EditText) findViewById(R.id.et_login_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_login_tellogin = (TextView) findViewById(R.id.tv_login_tellogin);
        tv_login_forget = (TextView) findViewById(R.id.tv_login_forget);
        ll_login = (LinearLayout) findViewById(R.id.ll_login);

        client = new OkHttpClient();
        jsonUtil = new JSONUtil();

    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            //登录按钮
            case R.id.btn_login:
                //登录方法
                getRSA();

                //测试 直接跳转主界面
//                intent = new Intent(LoginActivity.this, MainActivity.class);
//                startActivity(intent);

                break;
            //跳转到短信登录
            case R.id.tv_login_tellogin:
                intent = new Intent(LoginActivity.this, TelLoginActivity.class);
                startActivity(intent);

                break;
            //跳转到忘记密码
            case R.id.tv_login_forget:
                intent = new Intent(LoginActivity.this, ForgetActivity.class);
                startActivity(intent);

                break;
        }
    }

    /**
     * 1、获取main在窗体的可视区域
     * 2、获取main在窗体的不可视区域高度
     * 3、判断不可视区域高度
     * 1、大于100：键盘显示  获取Scroll的窗体坐标
     * 算出main需要滚动的高度，使scroll显示。
     * 2、小于100：键盘隐藏
     *
     * @param main   根布局
     * @param scroll 需要显示的最下方View
     */
    public void addLayoutListener(final View main, final View scroll) {
        main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                main.getWindowVisibleDisplayFrame(rect);
                int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
                if (mainInvisibleHeight > 150) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                    if (srollHeight > 0) {
                        main.scrollTo(0, srollHeight);
                    }
                } else {
                    main.scrollTo(0, 0);
                }
            }
        });
    }


    private String modulus;
    private String exponent;

    private void getRSA() {
        dialog = ProgressDialog.show(this, "提示", "正在登录，请稍后");
        Request request = new Request.Builder()
                .url(ContentUtil.RSA_url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        modulus = jsonObject.getJSONObject("data").getString("modulus");
                        exponent = jsonObject.getJSONObject("data").getString("exponent");
                        getTokenSalt();
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }


        });
    }

    /**
     * 获取token和salt
     */
    private String salt;
    private String token;

    private void getTokenSalt() {
        Request request = new Request.Builder()
                .url(ContentUtil.tokenSalt_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        salt = jsonObject.getJSONObject("data").getString("salt");
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(LoginActivity.this, "token", token);

                        login();

                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }
        });

    }

    private String phoneNo;
    private String password;
    private String password_real;

    private void login() {

        phoneNo = et_login_name.getText().toString();
        //密码限制+++++++++++++++++++++++++++++++++

        password = et_login_password.getText().toString();
        if (password.length() > 20) {
            toast("密码错误，请重新输入");
            return;
        }
        password_real = RSAPublicUtil.publicEncryptString(modulus, exponent, salt + password);
        String login = "?phoneNo=" + phoneNo + "&password=" + password_real;
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.login_url + login)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        String name = jsonObject.getJSONObject("data").getString("name");
                        String phoneNo = jsonObject.getJSONObject("data").getString("phoneNo");
                        SPUtil.setString(LoginActivity.this, "name", name);
                        SPUtil.setString(LoginActivity.this, "phoneNo", phoneNo);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
                Log.e(TAG, "登录联网成功" + jsonData);
            }
        });
    }


    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SysApplicationUtil.getInstance().deleteActivity(this);
    }
}
